import Vue from "vue";
import VueRouter from "vue-router";
import DashBoardView from "../views/dashBoardView.vue";
import loginView from "../views/loginView.vue";
import homeView from "@/views/homeView";
import userView from "@/views/userView";
import facilityView from "@/views/facilityView";
import facilityrepairView from "@/views/facilityrepairView";
Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/dashboard",
  },
  {
    path: "/dashboard",
    name: "dashboard",
    component: DashBoardView,
  },
  {
    path: "/login",
    name: "login",
    component: loginView,
  },
  {
    path: "/home",
    name: "home",
    component: homeView,
    redirect: "/home/user",
    children: [
      {
        path: "/home/user",
        name: "user",
        component: userView
      },
      {
        path: "/home/facility",
        name: "facility",
        component: facilityView
      }, {
        path: "/home/repair",
        name: "repair",
        component: facilityrepairView
      }
    ]
  }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  if (to.name === "login") {
    next();
  } else {
    const token = localStorage.getItem("token");
    if (token) {
      next();
    } else {
      next({ name: "login" });
    }
  }
});

export default router;
